import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import { useTranslation } from 'react-i18next';
import { request } from '../../src/api/request';
import eyes from '../assets/images/eyes.jpg';
import { jwtDecode, JwtPayload } from 'jwt-decode';
import { useNavigate } from 'react-router-dom';
import { messageApi } from '../hooks/messageApi';
import ToastNotification from './ToastNotification';
import { getDynamicFonts } from '@/utils/fontUtils';
import { motion, AnimatePresence } from 'framer-motion'; // 导入framer-motion动画库
import anime_girl_1 from '@/assets/images/login/4.webp'
import anime_girl_2 from '@/assets/images/login/5.webp'
import anime_man_1 from '@/assets/images/login/3.webp'
import anime_man_2 from '@/assets/images/login/6.webp'
import logo from '@/assets/images/logo.png'
import { getLoginModalImages, prerenderBackgroundElements } from '@/utils/imagePreloader';
// Custom JWT payload interface
interface CustomJwtPayload extends JwtPayload {
    displayName?: string;
    isFirstLogin?: boolean; // Add isFirstLogin field
    [key: string]: any;
}

interface LoginModalProps {
    show: boolean;
    onClose: () => void;
    onLoginSuccess?: () => void;
    activeTab?: string;
    aiAvatar?: string;
    initialRegister?: boolean;
}

const LoginModal: React.FC<LoginModalProps> = ({ show, onClose, onLoginSuccess, activeTab = 'anime_girl', aiAvatar, initialRegister = true }) => {
    const { t, i18n } = useTranslation();

    // Get dynamic fonts based on current language
    const dynamicFonts = getDynamicFonts(i18n);
    const navigate = useNavigate();
    const { show: showToast, message: toastMessage, type: toastType, showToast: displayToast } = messageApi();
    const [isRegister, setIsRegister] = useState(initialRegister);
    const [googleLoading, setGoogleLoading] = useState(false);
    const [showPassword, setShowPassword] = useState(true);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [emailLoading, setEmailLoading] = useState(false);
    
    // Verification code related states
    const [showVerificationForm, setShowVerificationForm] = useState(false);
    const [verificationCode, setVerificationCode] = useState(Array(6).fill('')); // 改为数组形式，确保始终有6个位置
    const [verificationLoading, setVerificationLoading] = useState(false);
    const [codeInputRefs, setCodeInputRefs] = useState<Array<React.RefObject<HTMLInputElement>>>([]);
    
    // Initialize six input field references
    useEffect(() => {
        const refs = Array(6).fill(0).map(() => React.createRef<HTMLInputElement>());
        setCodeInputRefs(refs);
    }, []);

    // Ensure background image displays immediately, no loading state needed
    const [backgroundRendered, setBackgroundRendered] = useState(true);

    // Get current background image URL to display
    const backgroundImageUrl = getBackgroundImage();

    // Get current language code
    const getLanguageCode = () => {
        switch (i18n.language) {
            case 'zh': return 'CN';
            case 'ja': return 'JP';
            default: return 'EN';
        }
    };

    // When component mounts, ensure background is pre-rendered
    useEffect(() => {
        // Ensure background elements are pre-rendered
        prerenderBackgroundElements();
    }, []);

    // Only sync isRegister when modal first opens
    const prevShowRef = useRef(show);
    useEffect(() => {
        if (!prevShowRef.current && show) {
            setIsRegister(initialRegister);
            // Reset verification code state
            setShowVerificationForm(false);
            setVerificationCode(Array(6).fill(''));
        }
        prevShowRef.current = show;
    }, [show, initialRegister]);

    // Display corresponding images based on selected tab menu
    function getBackgroundImage() {
        if (aiAvatar) return aiAvatar;
        if (activeTab === 'man') {
            return isRegister
                ? 'https://www.knomi.me/aiImgas/loginguys_1.jpg'
                : 'https://www.knomi.me/aiImgas/loginguys_2.jpg';
        } else if (activeTab === 'girl') {
            return isRegister
                ? 'https://www.knomi.me/aiImgas/loginGirl_1.jpg'
                : 'https://www.knomi.me/aiImgas/loginGirl_2.png';
        } else if (activeTab === 'anime_man') {
            return isRegister
                ? "https://www.knomi.me/aiImgas/3.webp"
                : "https://www.knomi.me/aiImgas/6.webp";
        } else if (activeTab === 'anime_girl') {
            return isRegister
                ? "https://www.knomi.me/aiImgas/4.webp"
                : "https://www.knomi.me/aiImgas/5.webp";
        }

        // Default image: if no matching activeTab or other cases, display default image
        return isRegister
            ? 'https://www.knomi.me/resource_AiPersion/G8/694be879-6fe9-479d-9103-af0a0998fa60.webp'
            : 'https://www.knomi.me/resource_AiPersion/G8/fb0c0ced-8788-4733-b9ce-39ac78075dd8.webp';
    }

    // Google login
    const loginByGoogle = async () => {
        setGoogleLoading(true);
        try {
            const res = await request.get('/auth/google-login-url');
            if (res.data.success && res.data.data.googleAuthUrl) {
                window.location.href = res.data.data.googleAuthUrl;
            } else {
                setGoogleLoading(false);
            }
        } catch {
            setGoogleLoading(false);
        }
    };

    // Process Google login callback data
    // This function would be called from the Google login callback component
    // or from the parent component that handles the OAuth redirect
    const processGoogleLoginData = (data: any) => {
        try {
            if (data && data.token) {
                const token = data.token;
                const decoded = jwtDecode<CustomJwtPayload>(token);
                
                // Store user data in localStorage
                const userData = {
                    visitor_uuid: data.uuid || '',
                    user_avatar: data.avatar || '',
                    visitor_token: token,
                    login_type: 'google',
                    user_email: data.email || decoded.email || '',
                    user_displayName: decoded.displayName || '',
                    last_chat_type: activeTab,
                    vip_live: decoded.membership_tier || null,
                    tokens_balance: data.tokens_balance || 0
                };
                
                localStorage.setItem('userData', JSON.stringify(userData));
                
                // Check if this is the user's first login
                if (decoded.isFirstLogin === true) {
                    localStorage.setItem('just_registered', 'true');
                }
                
                // Trigger event to notify other components
                window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));
                
                // Show success message and redirect
                displayToast(t('home.login.loginSuccess'), 'success');
                navigate('/');
            }
        } catch (error) {
            console.error('Failed to process Google login data:', error);
            displayToast(t('home.login.loginFailed'), 'error');
        }
    };

    // Enhanced email validation function
    const validateEmail = (email: string): { isValid: boolean; message?: string } => {
        // 1. Basic format check
        if (!email || email.trim() === '') {
            return { isValid: false, message: t('home.login.emailRequired') };
        }

        email = email.trim();

        // 2. Length check
        if (email.length > 254) {
            return { isValid: false, message: t('home.login.emailTooLong') };
        }

        // 3. Basic format check
        const basicPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!basicPattern.test(email)) {
            return { isValid: false, message: t('home.login.emailInvalidFormat') };
        }

        // 4. Stricter format check
        const strictPattern = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
        if (!strictPattern.test(email)) {
            return { isValid: false, message: t('home.login.emailInvalidChars') };
        }

        // 5. Check local part length (part before @)
        const [localPart, domainPart] = email.split('@');
        if (localPart.length > 64) {
            return { isValid: false, message: t('home.login.emailLocalTooLong') };
        }

        // 6. Check domain part
        if (domainPart.length > 253) {
            return { isValid: false, message: t('home.login.emailDomainTooLong') };
        }

        // 7. Check consecutive dots
        if (email.includes('..')) {
            return { isValid: false, message: t('home.login.emailConsecutiveDots') };
        }

        // 8. Check start and end
        if (email.startsWith('.') || email.endsWith('.') || email.startsWith('@') || email.endsWith('@')) {
            return { isValid: false, message: t('home.login.emailInvalidStartEnd') };
        }

        // 9. Check domain format
        const domainParts = domainPart.split('.');
        if (domainParts.length < 2) {
            return { isValid: false, message: t('home.login.emailInvalidDomain') };
        }

        // 10. Check top-level domain
        const tld = domainParts[domainParts.length - 1];
        if (tld.length < 2 || tld.length > 6) {
            return { isValid: false, message: t('home.login.emailInvalidTLD') };
        }

        // 11. Check common invalid domains
        const invalidDomains = ['test.com', 'example.com', 'temp.com', 'fake.com'];
        if (invalidDomains.includes(domainPart.toLowerCase())) {
            return { isValid: false, message: t('home.login.emailInvalidDomain') };
        }

        return { isValid: true };
    };

    // Send verification code
    const sendVerificationCode = async () => {
        if (!email || !password) return;

        // Use enhanced email validation
        const emailValidation = validateEmail(email);
        if (!emailValidation.isValid) {
            displayToast(emailValidation.message || t('home.login.emailInvalid'), 'error');
            return;
        }

        setEmailLoading(true);
        try {
            const language = getLanguageCode();
            const res = await request.post('/api/visitor/addUser',
                { email, password, language },
            );
            
            if (res.data.success) {
                displayToast(t('home.login.codeSent'), 'success');
                // 确保验证码表单显示
                console.log('设置验证码表单为可见');
                setShowVerificationForm(true);
                // 为确保状态更新生效，可以使用setTimeout
                setTimeout(() => {
                    console.log('验证码表单状态:', showVerificationForm);
                }, 100);
            } else {
                // console.log('Failed to send verification code:', res.data.message);
                displayToast(res.data.message || t('home.login.codeSendFailed'), 'error');
            }
        } catch (e) {
            const errorMessage = (e as any)?.response?.data?.message || t('home.login.codeSendFailedRetry');
            console.error('Failed to send verification code:', errorMessage);
            displayToast(errorMessage, 'error');
        } finally {
            setEmailLoading(false);
        }
    };

    // Handle verification code input changes
const handleVerificationCodeChange = (index: number, value: string) => {
    // 处理粘贴多位验证码的情况
    if (value.length > 1) {
        // 可能是粘贴了整个验证码
        const pastedValue = value;
        
        if (pastedValue.length >= 6) {
            // 用户粘贴了完整的验证码，分配到各个输入框
            const codeArray = pastedValue.slice(0, 6).split('');
            // 确保数组长度为6，不足的用空字符串补齐
            const newCodeArray = Array(6).fill('').map((_, i) => codeArray[i] || '');
            
            // 更新验证码数组状态
            setVerificationCode(newCodeArray);
            
            // 先聚焦最后一个输入框，确保焦点转移及时
                const lastRef = codeInputRefs[5];
                if (lastRef && lastRef.current) {
                    lastRef.current.focus();
                }
            
            // 使用requestAnimationFrame确保在下一个渲染帧中更新DOM
            requestAnimationFrame(() => {
                // 确保每个输入框显示正确的字符
                codeInputRefs.forEach((ref, i) => {
                    if (ref && ref.current && i < 6) {
                        ref.current.value = newCodeArray[i] || '';
                    }
                });
            });
            
            return;
        }
        
        // 如果不是完整的6位验证码，只取第一位
        value = value.charAt(0);
    }
    
    // 创建新的验证码数组副本
    const newCode = [...verificationCode];
    
    // 设置当前位置的值，只影响当前位置，不影响其他位置
    newCode[index] = value;
    
    // 更新状态
    setVerificationCode(newCode);
    
    // 首先自动聚焦下一个输入框，这样确保焦点转移的及时性
    if (value !== '' && index < 5) {
        // 立即聚焦到下一个输入框，不要放在异步回调中
            const nextRef = codeInputRefs[index + 1];
            if (nextRef && nextRef.current) {
                nextRef.current.focus();
            }
    }
    
    // 然后使用requestAnimationFrame确保在渲染后执行DOM更新
    requestAnimationFrame(() => {
        // 确保所有输入框都有正确的值，防止自动补位
        for (let i = 0; i < 6; i++) {
            const inputRef = codeInputRefs[i];
            if (inputRef && inputRef.current) {
                inputRef.current.value = newCode[i] || '';
            }
        }
    });
};

// Handle verification code input keyboard events
const handleCodeKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Backspace') {
        // 阻止默认行为，防止浏览器自带的自动补位
        e.preventDefault();
        
        // 创建新的验证码数组副本
            const newCode = [...verificationCode];
        
        if (verificationCode[index]) {
            // 当前输入框有内容时，只删除当前输入框的内容，其他位置保持不变
            newCode[index] = '';
            
            // 更新状态
            setVerificationCode(newCode);
            
            // 重新强制设置所有输入框的值，防止补位
            requestAnimationFrame(() => {
                // 确保所有输入框的值都正确设置，避免自动补位
                for (let i = 0; i < 6; i++) {
                    const inputRef = codeInputRefs[i];
                    if (inputRef && inputRef.current) {
                        inputRef.current.value = newCode[i] || '';
                    }
                    }
                });
        } else if (index > 0) {
            // 当前输入框为空时，向前聚焦并清空前一个输入框
            newCode[index-1] = '';
            
            // 先聚焦前一个输入框，确保焦点转移及时
                const prevRef = codeInputRefs[index-1];
                if (prevRef && prevRef.current) {
                    prevRef.current.focus();
            }
            
            // 更新状态
            setVerificationCode(newCode);
            
            // 使用RAF确保在渲染后执行DOM更新
            requestAnimationFrame(() => {
                // 确保所有输入框的显示值都正确设置，避免自动补位
                for (let i = 0; i < 6; i++) {
                        const inputRef = codeInputRefs[i];
                        if (inputRef && inputRef.current) {
                        inputRef.current.value = newCode[i] || '';
                    }
                        }
                    });
        }
    }
};

    // Verify email and register
    const verifyEmailAndRegister = async () => {
        const codeString = verificationCode.join('');
        if (!email || !password || !codeString || codeString.length !== 6) {
            displayToast(t('home.login.codeIncomplete'), 'error');
            return;
        }

        setVerificationLoading(true);
        try {
            const language = getLanguageCode();
            const res = await request.post('/api/visitor/verifyEmailAndRegister',
                { email, code: codeString, password, language },
            );
            
            if (res.data.success && res.data.data.token) {
                const token = res.data.data.token;
                const decoded = jwtDecode<CustomJwtPayload>(token);

                // Store user data as a single object in localStorage
                const userData = {
                    visitor_uuid: res.data.data.uuid,
                    user_avatar: res.data.data.avatar,
                    visitor_token: token,
                    login_type: 'google',
                    user_email: email,
                    user_displayName: decoded.displayName || '',
                    last_chat_type: activeTab,
                    vip_live: decoded.membership_tier || null,
                    tokens_balance: res.data.data.tokens_balance || 0
                };

                localStorage.setItem('userData', JSON.stringify(userData));

                // Trigger custom event to notify other components of login status change
                window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));

                // Show success message
                displayToast(t('home.login.registerSuccess'), 'success');

                // Set registration success flag
                localStorage.setItem('just_registered', 'true');

                // Close modal first, then callback to parent component
                if (typeof onClose === 'function') onClose();
                if (typeof onLoginSuccess === 'function') onLoginSuccess();
                localStorage.setItem('last_chat_type', activeTab);
                navigate('/');
            } else {
                // console.log('Registration failed:', res.data.message);
                displayToast(res.data.message || t('home.login.registerFailed'), 'error');
            }
        } catch (e) {
            // Handle error
            const errorMessage = (e as any)?.response?.data?.message || t('home.login.registerFailedRetry');
            console.error('Registration failed:', errorMessage);
            displayToast(errorMessage, 'error');
        } finally {
            setVerificationLoading(false);
        }
    };

    // Email login
    const loginByEmailUser = async () => {
        if (!email || !password) return;
        setEmailLoading(true);
        try {
            const language = getLanguageCode();
            const res = await request.post('/api/visitor/loginUser',
                { email, password, language },
            );
            if (res.data.success && res.data.data.token) {
                const token = res.data.data.token;
                const decoded = jwtDecode<CustomJwtPayload>(token);
                const userData = {
                    visitor_uuid: res.data.data.uuid,
                    user_avatar: res.data.data.avatar,
                    visitor_token: token,
                    login_type: 'google', // Keep login_type fixed as "google"
                    user_email: email,
                    user_displayName: decoded.displayName || '',
                    last_chat_type: activeTab,
                    vip_live: decoded.membership_tier || null
                };

                localStorage.setItem('userData', JSON.stringify(userData));
                
                // Check if this is the user's first login
                if (decoded.isFirstLogin === true) {
                    localStorage.setItem('just_registered', 'true');
                }
                
                // Trigger custom event to notify other components of login status change
                window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));

                // Show success message
                displayToast(t('home.login.loginSuccess'), 'success');

                // Close modal first, then callback to parent component
                if (typeof onClose === 'function') onClose();
                if (typeof onLoginSuccess === 'function') onLoginSuccess();
                localStorage.setItem('last_chat_type', activeTab);
                navigate('/');
            } else {
                console.error('Login failed')
                displayToast(res.data.message || t('home.login.loginFailed'), 'error');
            }
        }
        catch (e) {
            console.error('Login failed')
            // Handle error
            const errorMessage = (e as any)?.response?.data?.message || t('home.login.loginFailedRetry');
            console.error('Login failed:', errorMessage);
            displayToast(errorMessage, 'error');
        } finally {
            setEmailLoading(false);
        }
    };

    // Handle login/register button click
    const handleAuthButtonClick = () => {
        if (isRegister) {
            if (showVerificationForm) {
                verifyEmailAndRegister(); // Verify email and register
            } else {
                sendVerificationCode(); // Send verification code
            }
        } else {
            loginByEmailUser(); // Login
        }
    };

    

    // Header: left-aligned on mobile, centered on desktop
    const isMobile = typeof window !== 'undefined' && window.innerWidth <= 768;

    // 如果弹窗不显示，直接返回null
    if (!show) return null;

    // 使用ReactDOM.createPortal将弹窗渲染到body
    return ReactDOM.createPortal(
        <motion.div 
            className="fixed inset-0 z-50 flex items-center justify-center" 
            style={{ zIndex: 9500, fontFamily: dynamicFonts.font4 }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.3 }}
        >
            {/* Toast notification popup */}
            <ToastNotification
                show={showToast}
                message={toastMessage}
                type={toastType}
            />

                    {/* Backdrop with blur effect */}
                    <motion.div 
                        className="absolute inset-0 bg-black/70 backdrop-blur-sm" 
                        onClick={onClose}
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        transition={{ duration: 0.2 }}
                    />

                    {/* Modal with entrance animation */}
                    <motion.div 
                        className={`relative flex rounded-xl overflow-hidden max-w-3xl shadow-2xl min-h-[520px] ${isMobile ? 'w-full justify-center' : 'w-[90%]'}`}
                        initial={{ scale: 0.9, y: 20, opacity: 0 }}
                        animate={{ scale: 1, y: 0, opacity: 1 }}
                        exit={{ scale: 0.9, y: 20, opacity: 0 }}
                        transition={{ 
                            type: "spring", 
                            damping: 25, 
                            stiffness: 300,
                            duration: 0.4 
                        }}
                    >
                        {/* Left image (desktop only) with animation */}
                        <motion.div
                    className="hidden md:block md:w-1/2 bg-cover bg-center"
                    style={{
                        backgroundImage: `url(${backgroundImageUrl})`,
                        position: "relative",
                        transform: 'translateZ(0)',
                        willChange: 'background-image',
                        visibility: 'visible',
                        imageRendering: 'auto' as any,
                        contain: 'paint'
                    }}
                            initial={{ x: -50, opacity: 0 }}
                            animate={{ x: 0, opacity: 1 }}
                            transition={{ duration: 0.5, delay: 0.2 }}
                >
                    <div className="h-full w-full bg-gradient-to-r from-black/30 to-transparent">
                                <motion.div 
                                    className="absolute bottom-8 w-full flex justify-center"
                                    initial={{ y: 20, opacity: 0 }}
                                    animate={{ y: 0, opacity: 1 }}
                                    transition={{ duration: 0.6, delay: 0.4 }}
                                >
                                    <motion.div 
                                        className="text-white text-4xl font-bold"
                                        animate={{ 
                                            scale: [1, 1.05, 1],
                                            textShadow: [
                                                "0 0 0px rgba(255,255,255,0)",
                                                "0 0 10px rgba(255,255,255,0.5)",
                                                "0 0 0px rgba(255,255,255,0)"
                                            ]
                                        }}
                                        transition={{ 
                                            duration: 2, 
                                            repeat: Infinity, 
                                            repeatType: "reverse" 
                                        }}
                                    >
                                        {/* logo icon with pulse effect */}
                                <img src={logo} alt="logo" className="w-38 h-22 object-contain" />
                                    </motion.div>
                                </motion.div>
                            </div>
                        </motion.div>

                {/* Right form with animation */}
                <motion.div 
                    className={`relative bg-[#1A1A1A] p-8 ${isMobile ? 'w-[85%] mx-auto rounded-[1rem]' : 'w-full md:w-1/2'}`}
                    initial={{ x: isMobile ? 0 : 50, opacity: 0 }}
                    animate={{ x: 0, opacity: 1 }}
                    transition={{ duration: 0.5, delay: 0.2 }}
                >
                    {/* Close button with hover animation */}
                    <motion.div
                        onClick={onClose}
                        className="absolute top-4 right-4 text-gray-300 z-10"
                        whileHover={{ scale: 1.2, rotate: 90, color: '#ffffff' }}
                        whileTap={{ scale: 0.9 }}
                        transition={{ duration: 0.2 }}
                    >
                        <i className="fas fa-times text-xl" />
                    </motion.div>

                    {/* Header with animation */}
                    <motion.div 
                        className={`${isMobile ? 'mb-2 text-left' : 'mb-6 text-center md:text-left'}`}
                        initial={{ y: -20, opacity: 0 }}
                        animate={{ y: 0, opacity: 1 }}
                        transition={{ duration: 0.5, delay: 0.3 }}
                    >
                        <motion.h2 
                            className="text-2xl font-bold text-white"
                            layout
                            layoutId="modalTitle"
                            transition={{ type: "spring", stiffness: 300, damping: 30 }}
                        >
                            {isRegister ? t('home.login.createAccount') : t('loginModal.login')}
                        </motion.h2>
                    </motion.div>

                    {/* Form Inputs with staggered animations */}
                    <motion.div 
                        className="space-y-4 text-[0.85rem]" 
                        style={{ fontFamily: dynamicFonts.font2 }}
                        initial="hidden"
                        animate="visible"
                        variants={{
                            hidden: { opacity: 0 },
                            visible: { 
                                opacity: 1,
                                transition: { 
                                    staggerChildren: 0.1,
                                    delayChildren: 0.3
                                } 
                            }
                        }}
                    >
                        {/* 根据条件显示不同的表单内容 */}
                        <AnimatePresence mode="wait">
                        {!showVerificationForm ? (
                                <motion.div
                                    key="loginForm"
                                    initial={{ opacity: 0 }}
                                    animate={{ opacity: 1 }}
                                    exit={{ opacity: 0 }}
                                >
                                    {/* Email input field with animation */}
                                    <motion.div 
                                        className="relative mb-6" // 增加mb-6以拉开与下方密码输入框的距离
                                        variants={{
                                            hidden: { y: 20, opacity: 0 },
                                            visible: { y: 0, opacity: 1 }
                                        }}
                                    >
                                        <motion.div 
                                            className="absolute inset-y-0 left-3 flex items-center pointer-events-none text-gray-500"
                                            animate={{ 
                                                x: [0, 2, 0, -2, 0], 
                                                rotate: [0, 5, 0, -5, 0] 
                                            }}
                                            transition={{ 
                                                duration: 0.5,
                                                delay: 0.8
                                            }}
                                        >
                                        <i className="fas fa-envelope text-[1.2rem]" style={{ color: "rgb(141,141,141)" }}></i>
                                        </motion.div>
                                        <motion.input
                                        type="email"
                                        value={email}
                                        onChange={e => setEmail(e.target.value)}
                                        onKeyDown={(e) => {
                                            if (e.key === 'Enter') {
                                                e.preventDefault();
                                                handleAuthButtonClick();
                                            }
                                        }}
                                        placeholder={t('common.email', 'E-mail')}
                                        className={`w-full text-[0.85rem] placeholder-[rgb(224,224,224)] bg-[#1A1A1A] border border-[rgb(72,72,72)] rounded-xl py-3 pl-10 text-white focus:outline-none focus:border-pink-500 ${isMobile ? 'text-[16px]' : ''}`}
                                        style={{ backgroundColor: "rgb(37,37,37)" }}
                                            whileFocus={{ 
                                                boxShadow: "0 0 0 2px rgba(236, 72, 153, 0.3)", 
                                                borderColor: "rgb(236, 72, 153)"
                                            }}
                                        />
                                    </motion.div>
                                    
                                    {/* Password input field with animation */}
                                    <motion.div 
                                        className="relative mb-8"
                                        variants={{
                                            hidden: { y: 20, opacity: 0 },
                                            visible: { y: 0, opacity: 1 }
                                        }}
                                    >
                                        <motion.div 
                                            className="absolute inset-y-0 left-3 flex items-center pointer-events-none text-gray-500"
                                            animate={{ 
                                                x: [0, 2, 0, -2, 0], 
                                                rotate: [0, 5, 0, -5, 0] 
                                            }}
                                            transition={{ 
                                                duration: 0.5,
                                                delay: 1
                                            }}
                                        >
                                        <i className="fas fa-lock text-[1.2rem]" style={{ color: "rgb(141,141,141)" }}></i>
                                        </motion.div>
                                        <motion.input
                                        type={showPassword ? "text" : "password"}
                                        value={password}
                                        onChange={e => setPassword(e.target.value)}
                                        onKeyDown={(e) => {
                                            if (e.key === 'Enter') {
                                                e.preventDefault();
                                                handleAuthButtonClick();
                                            }
                                        }}
                                        placeholder={t('common.password', 'Password')}
                                        className={`w-full bg-[#1A1A1A] border border-[rgb(72,72,72)] rounded-xl py-3 pl-10 pr-10 placeholder-[rgb(224,224,224)] text-white focus:outline-none focus:border-pink-500 ${isMobile ? 'text-[16px]' : ''}`}
                                            style={{ backgroundColor: "rgb(37,37,37)", color: "white", textShadow: "0 0 0 white" }}
                                            whileFocus={{ 
                                                boxShadow: "0 0 0 2px rgba(236, 72, 153, 0.3)", 
                                                borderColor: "rgb(236, 72, 153)"
                                            }}
                                        />
                                        <motion.div
                                        className="absolute inset-y-0 right-3 flex items-center cursor-pointer text-gray-500"
                                        onClick={() => setShowPassword(!showPassword)}
                                            whileHover={{ scale: 1.1 }}
                                            whileTap={{ scale: 0.9 }}
                                    >
                                        <i className={`fas fa-${showPassword ? 'eye-slash' : 'eye'}`} style={{ color: "rgb(255,255,255)" }}></i>
                                        </motion.div>
                                    </motion.div>
                                    {/* Password hint below with animation */}
                                    <motion.div 
                                        style={{
                                    fontSize: '0.85rem',
                                    color: 'white !important',
                                    cursor: isRegister ? 'default' : 'pointer',
                                    marginBottom: '0rem',
                                    minHeight: '1.2em',
                                    textAlign: 'left',
                                    marginLeft: '0.5rem',
                                    marginTop: '0.5rem'
                                        }} 
                                        onClick={() => { if (!isRegister) { onClose(); navigate('/forget-password'); } }}
                                        variants={{
                                            hidden: { y: 10, opacity: 0 },
                                            visible: { y: 0, opacity: 1 }
                                        }}
                                        whileHover={!isRegister ? { 
                                            scale: 1.02,
                                            color: 'rgba(255, 255, 255, 1)',
                                            textShadow: "0px 0px 8px rgba(255,255,255,0.3)"
                                        } : {}}
                                    >
                                    {isRegister ? (
                                        t('home.login.passwordHint', 'Minimum 6 characters')
                                    ) : (
                                        i18n.language === 'ja' ? (
                                                <motion.span
                                                    animate={{ color: ['#ffffff', '#f87171', '#ffffff'] }}
                                                    transition={{ duration: 2, repeat: Infinity }}
                                                >
                                                    パスワードをお忘れですか？
                                                </motion.span>
                                            ) : (
                                                <motion.span
                                                    className="flex items-center"
                                                    animate={{ color: ['#ffffff', '#f87171', '#ffffff'] }}
                                                    transition={{ duration: 2, repeat: Infinity }}
                                                >
                                                <span style={{ textDecoration: 'underline' }}>For</span>g<span style={{ textDecoration: 'underline' }}>ot</span><span className='ml-[0.15rem]'>p</span><span style={{ textDecoration: 'underline' }}>assword?</span>
                                                </motion.span>
                                            )
                                        )}
                                    </motion.div>
                                </motion.div>
                            ) : (
                                <motion.div
                                    key="verificationForm" 
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    exit={{ opacity: 0, y: -20 }}
                                    transition={{ duration: 0.3 }}
                                    className="verification-form-container"
                                >
                                    {/* Verification code input fields with animations */}
                                    <motion.div 
                                        className="text-center mb-4 text-white"
                                    >
                                        <motion.p
                                            animate={{ 
                                                scale: [1, 1.03, 1],
                                                textShadow: ["0px 0px 0px rgba(255,255,255,0)", "0px 0px 8px rgba(255,255,255,0.5)", "0px 0px 0px rgba(255,255,255,0)"]
                                            }}
                                            transition={{ duration: 2, repeat: Infinity }}
                                        >
                                            {t('home.login.verificationCodeSent')}
                                        </motion.p>
                                    <p className="text-sm text-gray-400">{email}</p>
                                    </motion.div>
                                    
                                    {/* Verification code inputs with stagger animation */}
                                <div className="flex justify-center gap-2 mb-8">
                                    {[0, 1, 2, 3, 4, 5].map((index) => (
                                            <motion.div
                                            key={index}
                                                initial={{ y: 20, opacity: 0, scale: 0.8 }}
                                                animate={{ y: 0, opacity: 1, scale: 1 }}
                                                transition={{
                                                    type: "spring",
                                                    stiffness: 300,
                                                    damping: 20,
                                                    delay: index * 0.1
                                                }}
                                            >
                                                <motion.input
                                            ref={codeInputRefs[index]}
                                            type="text"
                                            maxLength={1}
                                            className="w-10 h-12 text-center text-lg bg-[#252525] border border-[rgb(72,72,72)] rounded text-white focus:outline-none focus:border-pink-500"
                                            value={verificationCode[index] || ''}
                                            onChange={(e) => handleVerificationCodeChange(index, e.target.value)}
                                            onKeyDown={(e) => handleCodeKeyDown(index, e)}
                                                    whileFocus={{
                                                        scale: 1.05,
                                                        boxShadow: "0 0 0 2px rgba(236, 72, 153, 0.5)",
                                                        borderColor: "rgb(236, 72, 153)"
                                                    }}
                                                    animate={
                                                        verificationCode[index] 
                                                        ? { 
                                                            backgroundColor: ["rgb(37,37,37)", "rgb(46,16,101)", "rgb(37,37,37)"],
                                                            transition: { duration: 1.5 }
                                                        } 
                                                        : {}
                                                    }
                                            onPaste={(e) => {
                                                e.preventDefault();
                                                const pastedData = e.clipboardData.getData('text').trim();
                                                if (pastedData) {
                                                        // 使用我们优化后的handleVerificationCodeChange处理粘贴的数据
                                                    handleVerificationCodeChange(index, pastedData);
                                                        
                                                        // 如果输入了单个字符，自动聚焦下一个输入框
                                                        if (pastedData.length === 1 && index < 5) {
                                                            const nextRef = codeInputRefs[index + 1];
                                                            if (nextRef && nextRef.current) {
                                                                nextRef.current.focus();
                                                            }
                                                        }
                                                        
                                                        // 添加额外的保护措施，确保在下一个渲染周期后，输入框的值是正确的
                                                        requestAnimationFrame(() => {
                                                            // 确保所有输入框的值与验证码状态同步
                                                            for (let i = 0; i < 6; i++) {
                                                                const inputRef = codeInputRefs[i];
                                                                if (inputRef && inputRef.current) {
                                                                    inputRef.current.value = verificationCode[i] || '';
                                                                }
                                                            }
                                                        });
                                                }
                                            }}
                                        />
                                            </motion.div>
                                    ))}
                                </div>
                                    
                                    {/* Resend button with animation */}
                                    <motion.div 
                                        className="text-center"
                                        initial={{ opacity: 0 }}
                                        animate={{ opacity: 1 }}
                                        transition={{ delay: 0.7 }}
                                    >
                                        <motion.button
                                        type="button"
                                            className="text-sm text-gray-400"
                                        onClick={() => sendVerificationCode()}
                                        disabled={emailLoading}
                                            whileHover={{ 
                                                scale: 1.05,
                                                color: "#ffffff",
                                                textShadow: "0px 0px 8px rgba(255,255,255,0.5)" 
                                            }}
                                            whileTap={{ scale: 0.95 }}
                                        >
                                            {emailLoading ? (
                                                <motion.span
                                                    animate={{ opacity: [0.5, 1, 0.5] }}
                                                    transition={{ duration: 1.5, repeat: Infinity }}
                                                >
                                                    {t('common.sending')}
                                                </motion.span>
                                            ) : (
                                                t('home.login.resendCode')
                                            )}
                                        </motion.button>
                                    </motion.div>
                                </motion.div>
                            )}
                        </AnimatePresence>
                        {/* Login/Register button with animations */}
                        <motion.button
                            type="button"
                            style={{ fontFamily: dynamicFonts.font4, marginTop: "1.2rem" }}
                            className="w-full bg-[rgb(231,82,117)] text-white py-3 rounded-lg font-medium mb-8 relative overflow-hidden"
                            onClick={handleAuthButtonClick}
                            disabled={emailLoading || verificationLoading}
                            variants={{
                                hidden: { y: 20, opacity: 0 },
                                visible: { y: 0, opacity: 1 }
                            }}
                            whileHover={!(emailLoading || verificationLoading) ? { 
                                scale: 1.03,
                                boxShadow: "0px 0px 15px rgba(231,82,117,0.6)"
                            } : {}}
                            whileTap={!(emailLoading || verificationLoading) ? { 
                                scale: 0.98,
                                boxShadow: "0px 0px 5px rgba(231,82,117,0.4)"
                            } : {}}
                            transition={{ 
                                type: "spring",
                                stiffness: 500,
                                damping: 15
                            }}
                        >
                            {/* Gradient hover effect */}
                            <motion.div
                                className="absolute inset-0 bg-gradient-to-r from-pink-500/20 via-purple-500/20 to-pink-500/20"
                                initial={{ x: "-100%" }}
                                animate={{ x: "100%" }}
                                transition={{ 
                                    repeat: Infinity, 
                                    duration: 1.5,
                                    ease: "linear"
                                }}
                            />
                            
                            {/* Button text */}
                            <motion.span className="relative z-10">
                                {emailLoading || verificationLoading ? (
                                    <motion.div 
                                        className="flex items-center justify-center space-x-2"
                                        initial={{ opacity: 1 }}
                                        animate={{ opacity: [0.7, 1, 0.7] }}
                                        transition={{ duration: 1.2, repeat: Infinity }}
                                    >
                                        <motion.span
                                            animate={{ scale: [1, 1.2, 1] }}
                                            transition={{ duration: 0.5, repeat: Infinity }}
                                        >
                                            {t('common.loading')}
                                        </motion.span>
                                        <motion.span 
                                            className="flex space-x-1"
                                            animate={{
                                                opacity: [0, 1, 0]
                                            }}
                                            transition={{ duration: 1.5, repeat: Infinity, repeatType: "loop" }}
                                        >
                                            {[0, 1, 2].map(i => (
                                                <motion.span 
                                                    key={i}
                                                    animate={{ y: [0, -3, 0] }}
                                                    transition={{ 
                                                        duration: 0.5, 
                                                        repeat: Infinity, 
                                                        repeatType: "mirror", 
                                                        delay: i * 0.1 
                                                    }}
                                                >
                                                    .
                                                </motion.span>
                                            ))}
                                        </motion.span>
                                    </motion.div>
                                ) : (
                                    isRegister ? (
                                        showVerificationForm ? (
                                            <motion.span
                                                initial={{ opacity: 0, y: 5 }}
                                                animate={{ opacity: 1, y: 0 }}
                                                exit={{ opacity: 0, y: -5 }}
                                                key="verify"
                                            >
                                                {t('home.login.verify')}
                                            </motion.span>
                                        ) : (
                                            <motion.span
                                                initial={{ opacity: 0, y: 5 }}
                                                animate={{ opacity: 1, y: 0 }}
                                                exit={{ opacity: 0, y: -5 }}
                                                key="getCode"
                                            >
                                                {t('home.login.getVerificationCode')}
                                            </motion.span>
                                        )
                                    ) : (
                                        <motion.span
                                            initial={{ opacity: 0, y: 5 }}
                                            animate={{ opacity: 1, y: 0 }}
                                            exit={{ opacity: 0, y: -5 }}
                                            key="signIn"
                                        >
                                            {t('home.login.signIn')}
                                        </motion.span>
                                    )
                                )}
                            </motion.span>
                        </motion.button>

                        {/* Divider with animation */}
                        <motion.div 
                            className="flex items-center" 
                            style={{ fontFamily: dynamicFonts.font1, marginTop: "1.2rem" }}
                            variants={{
                                hidden: { opacity: 0 },
                                visible: { opacity: 1 }
                            }}
                        >
                                                            <motion.hr 
                                className="flex-grow h-[2px] border-0" 
                                style={{ background: 'linear-gradient(to right, rgb(26,26,26), rgb(92,92,92))' }}
                                initial={{ width: 0 }}
                                animate={{ width: '20%' }}
                                transition={{ duration: 0.5, delay: 0.5 }}
                            />
                            <motion.span 
                                className="px-3 text-[0.9rem] text-white-500"
                                initial={{ opacity: 0, scale: 0.8 }}
                                animate={{ opacity: 1, scale: 1 }}
                                transition={{ duration: 0.3, delay: 0.7 }}
                            >
                                {isRegister ? t('home.login.orContinueWith', 'or continue with') : t('home.login.orSignInWith', 'or sign in with')}
                            </motion.span>
                            <motion.hr 
                                className="flex-grow h-[2px] border-0" 
                                style={{ background: 'linear-gradient(to right, rgb(92,92,92), rgb(26,26,26))' }}
                                initial={{ width: 0 }}
                                animate={{ width: '20%' }}
                                transition={{ duration: 0.5, delay: 0.5 }}
                            />
                        </motion.div>

                        {/* Social Login Buttons with animation */}
                        <motion.div 
                            className="grid grid-cols-1 gap-3 text-[1rem]" 
                            style={{ fontFamily: dynamicFonts.font2, marginTop: "1.2rem" }}
                            variants={{
                                hidden: { y: 20, opacity: 0 },
                                visible: { y: 0, opacity: 1, transition: { delay: 0.8 } }
                            }}
                        >
                            {/* Google Button with animation */}
                            <motion.button
                                type="button"
                                onClick={loginByGoogle}
                                className="flex items-center justify-center gap-2 bg-white text-gray-800 py-2 px-4 rounded-lg relative overflow-hidden"
                                whileHover={{ 
                                    scale: 1.03,
                                    boxShadow: "0px 0px 10px rgba(255,255,255,0.3)"
                                }}
                                whileTap={{ scale: 0.97 }}
                            >
                                {/* Subtle background animation */}
                                <motion.div 
                                    className="absolute inset-0 bg-gradient-to-r from-transparent via-gray-200 to-transparent"
                                    initial={{ x: '-100%', opacity: 0.3 }}
                                    animate={{ x: '100%', opacity: 0.3 }}
                                    transition={{ repeat: Infinity, duration: 2, ease: "linear" }}
                                />
                                
                                {googleLoading ? (
                                    <motion.div 
                                        className="w-5 h-5 border-2 border-t-transparent rounded-full"
                                        animate={{ 
                                            rotate: 360,
                                            borderColor: ["rgba(59, 130, 246, 0.5)", "rgba(236, 72, 153, 0.5)", "rgba(59, 130, 246, 0.5)"]
                                        }}
                                        transition={{ 
                                            rotate: { repeat: Infinity, duration: 1, ease: "linear" },
                                            borderColor: { repeat: Infinity, duration: 2 }
                                        }}
                                    />
                                ) : (
                                    <motion.svg 
                                        className="w-5 h-5 relative z-10" 
                                        viewBox="0 0 24 24"
                                        animate={{ 
                                            rotate: [0, 10, -10, 0],
                                            scale: [1, 1.1, 1]
                                        }}
                                        transition={{ 
                                            duration: 1.5, 
                                            delay: 1,
                                            repeatDelay: 5, 
                                            repeat: Infinity,
                                            repeatType: "mirror" 
                                        }}
                                    >
                                        <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                                        <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                                        <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                                        <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                                    </motion.svg>
                                )}
                                <motion.span 
                                    className="font-medium relative z-10"
                                    animate={googleLoading ? { opacity: [0.7, 1, 0.7] } : {}}
                                    transition={{ duration: 1.5, repeat: Infinity }}
                                >
                                    {t('home.login.googleButton', 'Google')}
                                </motion.span>
                            </motion.button>
                        </motion.div>

                        {/* Terms with animation */}
                        {isRegister && (
                            <motion.div 
                                style={{ marginTop: "1.2rem" }} 
                                className="mt-32 text-center text-[0.65rem] text-[rgb(164,164,164)]"
                                initial={{ opacity: 0, y: 10 }}
                                animate={{ opacity: 1, y: 0 }}
                                transition={{ delay: 1 }}
                            >
                                <motion.span
                                    animate={{ color: ["rgb(164,164,164)", "rgb(200,200,200)", "rgb(164,164,164)"] }}
                                    transition={{ duration: 4, repeat: Infinity }}
                                >
                                {t('home.login.agreement', 'By signing up, you agree to')}
                                    <motion.a 
                                        href="#" 
                                        className="text-[rgb(164,164,164)] underline ml-1"
                                        whileHover={{ 
                                            color: "#ffffff",
                                            textShadow: "0px 0px 5px rgba(255,255,255,0.5)"
                                        }}
                                    >
                                        {t('home.login.terms', 'Terms of Service')}
                                    </motion.a>
                                </motion.span>
                            </motion.div>
                        )}

                    </motion.div>

                    {/* Divider with glow animation */}
                    <motion.hr 
                        className={`absolute left-0 right-0 border-0 h-[2px] ${isMobile ? 'my-10' : 'my-24'}`} 
                        style={{ width: '100%' }}
                        initial={{ backgroundColor: "rgba(72,72,72,0.3)" }}
                        animate={{ 
                            backgroundColor: ["rgba(72,72,72,0.3)", "rgba(236,72,153,0.3)", "rgba(72,72,72,0.3)"],
                            boxShadow: [
                                "0 0 0px rgba(236,72,153,0)", 
                                "0 0 10px rgba(236,72,153,0.3)", 
                                "0 0 0px rgba(236,72,153,0)"
                            ] 
                        }}
                        transition={{ duration: 3, repeat: Infinity }}
                    />

                    {/* Already have account/Switch prompt with animation */}
                    <motion.div 
                        className={`text-center ${isMobile ? 'text-[0.8rem]' : 'text-[0.9rem]'} text-[rgb(255,255,255)] ${isMobile ? 'mt-16' : 'my-32'}`}
                        style={{ fontFamily: dynamicFonts.font3 }}
                        variants={{
                            hidden: { opacity: 0, y: 20 },
                            visible: { opacity: 1, y: 0 }
                        }}
                        transition={{ delay: 0.5, duration: 0.5 }}
                    >
                        <AnimatePresence mode="wait">
                            <motion.p 
                                key={isRegister ? "register" : "login"}
                                className="text-[255,255,255] flex items-center justify-center"
                                initial={{ opacity: 0, y: 10 }}
                                animate={{ opacity: 1, y: 0 }}
                                exit={{ opacity: 0, y: -10 }}
                                transition={{ duration: 0.3 }}
                            >
                            {isRegister ? (
                                <>
                                    {t('home.login.alreadyHaveAccountTip', "Already have an account yet?")}
                                        <motion.span
                                        className="cursor-pointer"
                                        style={{ color: 'rgb(231,82,91)', marginLeft: '0.5rem' }}
                                        onClick={() => setIsRegister(false)}
                                            whileHover={{ 
                                                scale: 1.05, 
                                                color: "rgb(252,118,138)",
                                                textShadow: "0px 0px 8px rgba(252,118,138,0.5)" 
                                            }}
                                            whileTap={{ scale: 0.95 }}
                                    >
                                        {t('home.login.signIn', 'Sign in')}
                                        </motion.span>
                                </>
                            ) : (
                                <>
                                    {t('home.login.dontHaveAccountTip', "Don't have an account yet?")}
                                        <motion.span
                                        className="cursor-pointer"
                                        style={{ color: 'rgb(231,82,91)', marginLeft: '1rem' }}
                                        onClick={() => setIsRegister(true)}
                                            whileHover={{ 
                                                scale: 1.05, 
                                                color: "rgb(252,118,138)",
                                                textShadow: "0px 0px 8px rgba(252,118,138,0.5)" 
                                            }}
                                            whileTap={{ scale: 0.95 }}
                                    >
                                        {t('home.login.signUp', 'Sign up')}
                                        </motion.span>
                                </>
                            )}
                            </motion.p>
                        </AnimatePresence>
                    </motion.div>
                </motion.div>
            </motion.div>
        </motion.div>,
        document.body
    );
};

export default LoginModal; 